package com.w3coffee.web.control;

import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class IdentityAuthenticationFilter implements Filter {
	protected FilterConfig filterConfig = null;
	private String loginUrl = null;

	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;

		String cp = filterConfig.getServletContext().getContextPath();
		if (cp == null) {
			loginUrl = "/checkin.sf";
		} else if (cp.length() == 0) {
			loginUrl = "/checkin.sf";
		} else {
			loginUrl = cp + "/checkin.sf";
		}
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse rsp = (HttpServletResponse) response;

		if (needAuthenticate(req)) {
			StringBuffer buf = new StringBuffer(loginUrl);
			buf.append("?backUrl=").append(URLEncoder.encode(getBackUrl(req), "UTF-8"));
			// 重定向到登录服务页面
			rsp.sendRedirect(buf.toString());
		} else {
			chain.doFilter(request, response);
		}
	}

	public void destroy() {
		this.filterConfig = null;
	}

	private String getBackUrl(HttpServletRequest req) {
		StringBuffer backUrl = new StringBuffer();
		backUrl.append(req.getRequestURL());

		String qs = req.getQueryString();
		if (qs != null) {
			backUrl.append('?').append(qs);
		}
		return backUrl.toString();
	}

	private boolean needAuthenticate(HttpServletRequest req) {
		StringBuffer url = req.getRequestURL();
		System.out.println("-> " + url);
		int posi = url.lastIndexOf("/");
		if (posi < 2) {
			return false;
		}

		char c1 = url.charAt(posi - 2);
		char c2 = url.charAt(posi - 1);
		if (c1 == '/' && c2 == 'a') { // 请求的URL在需要授权的目录下/a/
			HttpSession session = req.getSession(false);
			if (session == null) {
				return true;
			}
			
			CheckinToken token = (CheckinToken) session.getAttribute("TOKEN");
			if (token == null) {
				return true;
			} else {
				return token.getCheckinAction() != CheckinAction.already_checkin;
			}
		} else {
			return false;
		}
	}
}
